import {defineStore} from 'pinia'
import hi from "@/utils/hi";

interface StateType {
	info: object,
	roles: any[],
	hasLogin: boolean,
	// token: string,
	// tokenExpired: string
}

const uuid = hi.uuid;
const userInfoHistory = hi.storage.get('userinfo') || {};
// 用户accessToken
const token = hi.storage.get('userToken') || "";
// 用户accessToken的过期时间（毫秒级）
const tokenExpired = hi.storage.get('userTokenExpired') || 0;

//判断是否登陆
function hasLogin() {
	//Object.keys().length 判断对象长度，用以检测对象是否为空
	if (!Boolean(Object.keys(userInfoHistory).length)) return false;
	let timestamp = Date.now();
	return tokenExpired >= timestamp;
}

const username = userInfoHistory?.username || "";
const uid = userInfoHistory?.id || 0;

/**
 * 设置用户权限角色
 * guest: 访客
 * admin: 管理员
 * edit: 编辑
 */
function setRoles(data = null) {
	let user = data || username;
	if (!hasLogin()) return ["guest"];
	let roles = [];
	if (user.includes('admin')) {
		roles.push("admin");
	}
	roles.push("edit");
	return roles;
}

const store = {
	//是否已经登录
	hasLogin: hasLogin(),
	//用户信息
	info: userInfoHistory,
	//用户权限
	roles: setRoles(),
	token: token,
	tokenExpired: tokenExpired
}

/*
* userinfo结构
* uuid : 用户UUID(未登陆时为0，新用户会随机分配一个）
* uid:  数据库内id字段，该字段用于与服务器的交互，标明用户ID
* info: 数据库传回的完整用户数据
* token: 用户access_token
* tokenExpired: 用户access_token过期时间（毫秒）
* username: 用户名
* roles: 用户权限角色
* */
function userinfo() {
	return {
		uuid: uuid,
		uid: uid,
		username: username,
		roles: setRoles(),
		token: token,
		tokenExpired: tokenExpired,
	}
}

export const useStoreUser = defineStore("userinfo", {
	// state: (): StateType => <StateType>store,//store中子键与interface中声明的不一致时，用该方法一并重新申明
	state: (): StateType => (store),
	getters: {
		info: (state): object => state.info,
		roles(state): any[] {
			return userinfo().roles;
		},
		hasLogin(state): boolean {
			return state.hasLogin;
		}
	},
	actions: {
		/*传入用户数据并设置*/
		Set(data: string) {
			this.info = data
			hi.storage.set("userinfo", data)
		},
		/*更新登陆状态*/
		login(state, data) {
			return new Promise((resolve, reject) => {
				//将原有信息与新传来的参数进行合并
				let _info = state.info;
				state.info = {..._info, ...data};
				//设置为已经登录
				state.hasLogin = true;
				//存储最新的用户数据到本地持久化存储
				hi.storage.set("userinfo", state.info);
				// 将传入的token、tokenExpired写入更新
				let token = data.token ? data.token : false
				if (data.token) {
					hi.storage.set("userToken", data.token);
					hi.storage.set("userTokenExpired", state.info.tokenExpired);
				}
				//更新权限
				setRoles(data.username);
				resolve(state)
			})
		},

		logout() {
			return new Promise((resolve, reject) => {
				//清除相应缓存
				hi.storage.set("userinfo", {});
				hi.storage.set("userToken", "");
				hi.storage.set("userTokenExpired", 0);
				resolve(true)
			})
		}
	}
})

export default useStoreUser;
